package fr.afcepf.atod18.utilitaires.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public abstract class AbstractHibernateDao< T >{
	   private Class< T > clazz;

	   @Autowired
	   private SessionFactory sessionFactory;

	   @SuppressWarnings("unchecked")
	   public T findOne( final int id ){
	      return (T) getCurrentSession().get( clazz, id );
	   }
	   @SuppressWarnings("unchecked")
	   public List< T > findAll(){
	      return getCurrentSession().createQuery( "from " + clazz.getName() ).list();
	   }

	   public void save( final T entity ){
	      getCurrentSession().persist( entity );
	   }

	   @SuppressWarnings("unchecked")
	   public T update( final T entity ){
	      return (T) getCurrentSession().merge( entity );
	   }

	   public void delete( final T entity ){
	      getCurrentSession().delete( entity );
	   }
	   public void deleteById( final int id ){
	      final T entity = findOne(id);
	      delete( entity );
	   }
       @SuppressWarnings("unchecked")
       public List<T> findByName(String nomColonne, String valeur) {
           return (List<T>) getCurrentSession().createCriteria(clazz).add(Restrictions.like(nomColonne, valeur, MatchMode.ANYWHERE)).list();
       }
       public void deleteList(List<T> list) {
           for(T entity : list) delete(entity);
       }
       
       public void setClazz( final Class< T > clazzToSet ){
           clazz = clazzToSet;
        }
	   protected final Session getCurrentSession(){
		   return sessionFactory.getCurrentSession();
	   }
	   public SessionFactory getSessionFactory() {
		   return sessionFactory;
	   }
	   public void setSessionFactory(SessionFactory sessionFactory) {
		   this.sessionFactory = sessionFactory;
	   }
	   
	}